package sfin.controller;

import sfin.service.CartaoService;
import sfin.service.ContaService;
import sfin.swt.exception.StatizoException;
import br.com.statizo.financeiro.domain.entity.impl.CartaoCredito;

public class CartaoController {

	private CartaoService service;

	private String nome = "";
	private int conta = -1;
	private int selectedIndex = -1;
	private ControllerUtil util;
	private ContaService contaService;
	
	public CartaoController(CartaoService service, ContaService contaService, ControllerUtil util) {
		this.service = service;
		this.util = util;
		this.contaService = contaService;
	}

	public String[][] getCartoes(){
		return service.getAll();
	}

	public int getConta() {
		return util.normalizeOptionToShow(conta);
	}

	public void setConta(int conta) {
		this.conta = conta;
	}

	public String getNome() {
		return nome;
	}

	public void setNome(String nome) {
		this.nome = nome;
	}

	public int getSelectedIndex() {
		return selectedIndex;
	}

	public void setSelectedIndex(int selectedIndex) {
		this.selectedIndex = selectedIndex;
		loadData();
	}

	public String[] getContas(){
		return util.includeSelectOption(contaService.getNomes());
	}

	public void callSave() throws StatizoException{
		this.selectedIndex = service.save(selectedIndex, nome, util.normalizeOptionToSave(conta));
		loadData();
	}

	public void clearSelection() {
		this.selectedIndex = -1;
		loadData();
	}

	private void loadData() {
		if(selectedIndex >=0){
			CartaoCredito cartao = service.getAt(selectedIndex);
			this.nome = cartao.getNome();
			this.conta = contaService.indexOf(cartao.getConta());
		}else{
			this.nome = "";
			this.conta = -1;
		}
	}

	public void callDel() throws StatizoException{
		service.delete(selectedIndex);
	}

	public boolean existeCartao() throws StatizoException{
		return service.count() > 0;
	}

}